package com.cjst.controller.api.article;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baidu.ueditor.UeditorChange;
import com.cjst.pojo.base.AlarmResult;
import com.cjst.pojo.base.Article;
import com.cjst.pojo.part.Parts;
import com.cjst.pojo.sys.SysUser;
import com.cjst.service.base.ArticleService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;
import com.cjst.util.ResultMap;
import com.cjst.util.common.DateUtil;
import com.cjst.util.common.ResultCode;
import com.cjst.util.json.ResultObj;

@Controller
@RequestMapping("/api/article")
public class ArticleController {
	private Logger log=Logger.getLogger(ArticleController.class);
	
	@Autowired
	private ArticleService articleService;
	@Value("${file.pathUe}")
	private String pathUe;
	
	@Value("${img.location}")
    private String fileUploadPath;
    @Value("${file.path}")
    private String filePath;
	
	@RequestMapping(value="/getArticleDetail",method = RequestMethod.POST)
	@ResponseBody
	public String getArticleDetail(String articleId){
		if(articleId==null) {
			ResultObj obj=new ResultObj(ResultCode.STATE_NULL, "error",null);
			
			return obj.toString();
		}
		WherePrams wherePrans=Method.where("id", C.EQ, articleId);
		Article article=articleService.get(wherePrans);
		String str="";
		if(article!=null){					///static/image
			String content=article.getContent();
			if(content!=null && content.length()>0){
				str=UeditorChange.changeStr(pathUe, content, "/static/imgWork");
				article.setContent(str);
			}
		}
		ResultObj obj=new ResultObj(ResultCode.STATE_SUCCESS, "success",article);
		
		return obj.toString();
	}
	@RequestMapping(value="/getArticleByCode",method = RequestMethod.POST)
	@ResponseBody
	public String getArticleByCode(String code,Integer type){
		
		if(type==null) {
			type=3;
		}
		
		WherePrams wherePrans=Method.where("isDelete", C.EQ, 0);
		wherePrans.and("type", C.EQ, type);
		if(code!=null&&!"".equals(code)) {
			wherePrans.and("num",C.EQ,code);
		}
		
		Article article=articleService.get(wherePrans);
		/*
		List<Article> articleList=articleService.list(wherePrans);
		if(articleList!=null && articleList.size()>0){
			
			for (Article article : articleList) {
				String str = "";
				if (article != null) { /// static/image
					String content = article.getContent();
					if (content != null && content.length() > 0) {
						str = UeditorChange.changeStr(pathUe, content, "/static/imgWork");
						article.setContent(str);
					}
				}
			}
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",articleList);
            return robj.toString();
		}else{
			ResultObj obj=new ResultObj(ResultCode.STATE_SUCCESS, "success",null);
			return obj.toString();
		}
		*/
		String str = "";
		if (article != null) { /// static/image
			String content = article.getContent();
			if (content != null && content.length() > 0) {
				str = UeditorChange.changeStr(pathUe, content, "/static/imgWork");
				article.setContent(str);
			}
		}
		ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",article);
        return robj.toString();
	}
	
	
	@RequestMapping(value="/getAllArticleByType",method = RequestMethod.POST)
	@ResponseBody
	public String getAllArticleByType(Integer type,String offerId){
		
//		Enumeration params = request.getParameterNames();
//		
//		while (params.hasMoreElements()) {
//			String name = params.nextElement().toString();				
//			// 得到参数对应值
//			String[] value = request.getParameterValues(name);
//			System.out.println("name:"+name.toString());
//			System.out.println("value:"+value[0]);
//		}
		
		if(type==null) {
			type=3;
		}
		WherePrams wherePrams=Method.where("isDelete",C.EQ,0);
		wherePrams.and("type", C.EQ, type);
		List<Article> articleList=articleService.list(wherePrams);
		if(articleList!=null && articleList.size()>0){
			for (Article article : articleList) {
			String str="";
				if (article != null) { /// static/image
					if (article.getTopUrl() != null) {
						article.setTopUrl(filePath + article.getTopUrl());
					}
					
					//首页banner无内容
//					if(type==2) {
//						article.setContent(null);
//						article.setContentText(null);
//					}
					
					String content = article.getContent();
					if (content != null && content.length() > 0) {						
						str = UeditorChange.changeStr(pathUe, content, "/static/imgWork");
						article.setContent(str);
					}
				}
			}
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",articleList);
            return robj.toString();
		}else{
			ResultObj obj=new ResultObj(ResultCode.STATE_SUCCESS, "success",null);
			return obj.toString();
		}
	}
	
	@RequestMapping(value = "/getArticleByPage", method = RequestMethod.POST)
	@ResponseBody
	public String getArticleByPage(Integer page,Integer size,Integer type) {
		if(page==null){
			page=0;
		}
		if(size==null){
			size=10;
		}
		if(size==0||page<1) {
			page=1;
			size=10;
		}	   		
		if(type==null) {
			type=3;
		}

		try {
			WherePrams wherePrams = Method.where("isDelete", C.EQ, 0);
			wherePrams.and("type", C.EQ, type);
			/**
			 * 限制返回数量 LIMIT
			 * 排序。、、、
			 * 排序。、、、
			 * 排序。、、、
			 */
			List<Article> articleList = articleService.listPage(wherePrams," ORDER BY create_time desc limit "+(page-1)*size+","+size);

			/**
			 * LIMIT次循环，填上设备地址 多表查询？
			 */
//			if (articles != null && articles.size() > 0) {
//				articles.forEach(tmp -> {
//
//				//	tmp.setImgUrl(begin_url + tmp.getImgUrl());
//
//				});
//			}
			
			if(articleList!=null && articleList.size()>0){
				
				articleList.forEach(article->{
					String str="";
					if(article!=null){					///static/image
						
						if(article.getTopUrl()!=null) {
							article.setTopUrl(filePath+article.getTopUrl());
						}
						String content=article.getContent();
						if(content!=null && content.length()>0){
							str=UeditorChange.changeStr(pathUe, content, "/static/imgWork");
							article.setContent(str);
						}
					}
					
				});
				
				ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success",articleList);
	            return robj.toString();
			}else{
				ResultObj obj=new ResultObj(ResultCode.STATE_SUCCESS, "success",null);
				return obj.toString();
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
			ResultObj robj = new ResultObj(ResultCode.RESULT_EXCEPTION, "网络异常", null);
			return robj.toString();
		}

	}
	
	@RequestMapping(value = "/getArticle", method = RequestMethod.POST)
	@ResponseBody
	public String getArticle() {
		WherePrams wherePrans = Method.where("num", C.EQ, 0);
		List<Article> articleList = articleService.list(wherePrans);
		if (articleList != null && articleList.size() > 0) {
			for (Article article : articleList) {
				String str = "";
				if (article != null) { /// static/image
					String content = article.getContent();
					if (content != null && content.length() > 0) {
						str = UeditorChange.changeStr(pathUe, content, "/static/imgWork");
						article.setContent(str);
					}
				}
			}
			ResultObj robj = new ResultObj(ResultCode.RESULT_SUCCESS, "success", articleList);
			return robj.toString();
		} else {
			ResultObj obj = new ResultObj(ResultCode.STATE_SUCCESS, "success", null);
			return obj.toString();
		}
	}
	
	@RequestMapping("/addArticle")
	public String addArticle(String content,Integer type,Integer isTop,String title,String contentText,String textSource,String topUrl,String num){
		//System.out.println("===============>>"+content);
		log.info("===============>>"+content);
		Article arc=new Article();
		arc.setType(type);
		arc.setContentText(contentText);
		arc.setContent(content);
		arc.setTitle(title);
		arc.setTextSource(textSource);
		arc.setIsTop(isTop);
		arc.setNum(num);
		arc.setNum(topUrl);
		arc.setCreateTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
		arc.setPx(new Date().getTime());
		SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		arc.setCreateUser(sysUser.getId());
		arc.setCreateName(sysUser.getName());
		articleService.addLocalByid(arc);
		return "article/toAddArticle";
	}
	
	
	@RequestMapping("/upload")
    @ResponseBody
    @Transactional
    public Object upload(HttpServletRequest request, MultipartFile file,String dirs) {
        try {

            //文件上传路径
            String serverPath = fileUploadPath;

            String uploadDir = "";

            //文件名称
            String fileName = file.getOriginalFilename();
            //文件后缀
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            if(dirs!=null && dirs.length()>0){
            	uploadDir = uploadDir + "/" + dirs + "/" + "avator";
            }else{
            	uploadDir = uploadDir + "/"  + "avator";
            }
            

            //检查目录是否存在
            File dir = new File(serverPath + uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //随机名称
            String randomFileName = UUID.randomUUID().toString();
            //文件存在服务器上的路径
            String fileUrl = uploadDir + "/" + randomFileName + "." + suffix;

            //将文件上传到文集的物理地址
            File serverFile = new File(serverPath + fileUrl);
            file.transferTo(serverFile);
            log.info("文件上传成功");
            HashMap<String, String> map=new HashMap<String, String>();
            map.put("fileUrl", fileUrl);
            map.put("filePath", filePath + fileUrl);
            return new ResultObj(1, "文件上传成功", map);

        } catch (Exception e) {
            log.error(e.getMessage());
            return new ResultObj(0, e.getMessage(), null);
        }

    }

}
